
from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler

# 自定义序列化器来完成针对登陆的username和password的校验
class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=20, required=True)
    password = serializers.CharField(min_length=8, max_length=20, required=True)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        # 校验用户名和密码 —— django传统身份校验
        # 功能：认证用户身份
        # 参数：username和password
        # 返回值：校验成功返回用户模型类对象，否则返回None
        user = authenticate(username=username, password=password)

        if not user:
            # 用户名或密码校验失败
            raise serializers.ValidationError("用户名或密码错误！")

        # TODO: 签发token
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 返回有效数据
        return {
            'user': user,
            'token': token
        }